package com.work.leecode.listNode.middle;

/**
 * 两数相加
 */
public class Lc2 {

    //短的列表补0
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //前置过滤校验
        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {
            return l1;
        }

        //新链表的头结点
        ListNode dummy = new ListNode(-1);

        //临时结点
        ListNode temp = dummy;

        //进位辅助变量
        int carry = 0;
        int value1;
        int value2;

        while (l1 != null || l2 != null) {
            //短的补0
            value1 = l1 != null ? l1.val : 0;
            value2 = l2 != null ? l2.val : 0;

            ListNode node = new ListNode((value1 + value2 + carry) % 10);
            temp.next = node;
            temp = temp.next;

            carry = (value1 + value2 + carry) / 10;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        //最后需要对carry单独进行判断
        if (carry == 1) {
            temp.next = new ListNode(1);
        }

        return dummy.next;
    }

    //复习2024.05.05
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {
            return l1;
        }

        //哑结点
        ListNode dummy = new ListNode(-1);
        //辅助结点
        ListNode temp = dummy;
        //进位
        int carry = 0;
        //链表值
        int a = 0;
        int b = 0;
        while (l1 != null || l2 != null) {
            //短的列表补0
            a = l1 != null ? l1.val : 0;
            b = l2 != null ? l2.val : 0;

            ListNode node = new ListNode((a + b + carry) % 10);
            carry = (a + b + carry) / 10;
            temp.next = node;
            temp = temp.next;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry == 1) {
            temp.next = new ListNode(1);
        }
        return dummy.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}

